package graphic.dialogs;

import graphic.MainFrame;
import graphic.mycomponents.TextChecked;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import utility.GraphicUtilsFactory;
import core.Function;

public class NewUserDialog extends AbstractDialog
{
	TextChecked userId;
	TextChecked password;
	
	public NewUserDialog()
	{	
		super("Create New User", "Create", 450, 200);
	}
	
	public void createPanel()
	{
		super.setPanel(new JPanel(new GridBagLayout()));
		
		JPanel panel = super.getPanel(); 
		
		this.userId = new TextChecked("", TextChecked.TEXT, true, false, Function.getUserNamesList());
		this.password = new TextChecked("", TextChecked.PASSWORD, true, false, null);
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.userId, "User Name");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.password, "Password");		
		
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.CENTER;
		c.insets = new Insets(5, 10, 5, 10);
		
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		panel.add(new JLabel("New User Creation"), c);
		
		c.gridx = 0;
		c.gridy = 1;
		panel.add(this.userId, c);		

		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 2;
		panel.add(this.password, c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 1;
		panel.add(super.getOkButton(), c);

		c.gridx = 1;
		c.gridy = 3;
		panel.add(super.getExitButton(), c);		
	}

	@Override
	public boolean checkOkFunction()
	{
		if(!this.userId.isChecked())
		{
			JOptionPane.showMessageDialog(this, "Please type a correct user name!", "Problem creating a new user!", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		if(!this.password.isChecked())
		{
			JOptionPane.showMessageDialog(this, "Please type a correct password!", "Problem creating a new user!", JOptionPane.ERROR_MESSAGE);
			return false;
		}

		return true;
	}

	@Override
	public void okFunction()
	{
		if(Function.addUser(this.userId.getText(), this.password.getText()))
		{
			super.dispose();
			MainFrame.getInstance().showMessage("New User Created!", JOptionPane.INFORMATION_MESSAGE);
		} else {
			super.dispose();
			MainFrame.getInstance().showMessage("New User NOT Created!", JOptionPane.ERROR_MESSAGE);
		}	
	}
}